package wh.coach.pivot3.table.dynamic;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import lombok.Getter;
import lombok.NoArgsConstructor;
import wh.coach.domain.CalType;

/**
 * @author xhw
 * @date 2024/1/20
 */

@NoArgsConstructor
public class DataGroups {
    @Getter
    private List<String> rowsKeys;
    @Getter
    private List<String> columnsKeys;

    public DataGroups(List<String> rowsKeys, List<String> columnsKeys) {
        this.rowsKeys = rowsKeys;
        this.columnsKeys = columnsKeys;
    }

    private final Map<GroupKey, List<DataRow>> groups = new TreeMap<>();

    public void addDataRow(final DataRow dataRow) {
        //提取DataRows的数据
        List<String> rows = rowsKeys.stream().map(key -> dataRow.getValue(key)).toList();
        List<String> columns = columnsKeys.stream().map(key -> dataRow.getValue(key)).toList();
        //行列分组
        GroupKey key = new GroupKey(rows, columns);
        //添加分组后的分数
        groups.computeIfAbsent(key, k -> new ArrayList<>()).add(dataRow);
    }

    //问题分析
    public Number calculate(final Aggregation aggregation , final GroupKey groupKey) {
        List<DataRow> rows = groups.get(groupKey);
            List<Number> scores = rows.stream()
                    .map(row -> row.getValue(aggregation.getFieId()))
                    .map(val -> Integer.parseInt(val))
                    .map(Number.class::cast)
                    .toList();
            AggregationValues aggregationValues = new AggregationValues(aggregation.getCalType(), scores);
        return aggregationValues.calculate();
    }
    public Set<GroupKey> getGroupKeys() {
        return groups.keySet();
    }
}






